package cn.springsoter.core.mp.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import cn.springsoter.core.mp.plugins.SqlLogInterceptor;

/**
 * MybatisPlus config
 * 
 * @author kevin
 */
@Configuration
public class MybatisPlusConfig {

	// 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        //乐观锁插件：只能作用在updateById和update(Entity, Wrapper)2个方法，Entity必须是从db查出来的对象，不能new一个新的
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        //防止全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }
    
    /**
     * 配置 sql打印拦截器
     * application.yml中 mybatis-plus.print-sql: true 时生效
     *
     * @return SqlLogInterceptor
     */
    @Bean
    @ConditionalOnProperty(name = "mybatis-plus.print-sql", havingValue = "true")
    public SqlLogInterceptor sqlLogInterceptor() {
        return new SqlLogInterceptor();
    }
}
